import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'core/app.dart';
import 'core/app_initializer.dart';
import 'data/datasources/local/auth_local_data_source.dart';
import 'presentation/providers/dependencies.dart';
import 'dart:io';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化本地存储
  try {
    await Hive.initFlutter();
    debugPrint('Hive初始化成功');
  } catch (e) {
    debugPrint('Hive初始化失败: $e');
  }

  // 初始化认证本地数据源
  final authLocalDataSource = AuthLocalDataSource();
  try {
    await authLocalDataSource.initialize();
    debugPrint('认证本地数据源初始化成功');
    // 添加调试信息
    debugPrint('认证本地数据源Box是否打开: ${authLocalDataSource.isBoxOpen}');

    // 检查Hive是否已初始化
    bool isHiveInitialized = Hive.isBoxOpen('auth');
    print('Hive auth box是否打开: $isHiveInitialized');

    // 获取Box实例并检查其状态
    if (Hive.isBoxOpen('auth')) {
      var box = Hive.box('auth');
      print('Box中的键数量: ${box.length}');
      print('Box中的所有键: ${box.keys}');
    }
  } catch (e) {
    debugPrint('认证本地数据源初始化失败: $e');
    // 尝试关闭可能存在的锁文件
    try {
      // 使用默认的Hive路径
      final documentsDir = await Directory.systemTemp.createTemp('hive_');
      final lockFile = File('${documentsDir.path}/auth.lock');
      if (await lockFile.exists()) {
        await lockFile.delete();
        debugPrint('删除了锁文件');
        // 重新尝试初始化
        await authLocalDataSource.initialize();
        debugPrint('重新初始化认证本地数据源成功');
      }
    } catch (innerE) {
      debugPrint('处理锁文件时出错: $innerE');
    }
  }

  runApp(
    ProviderScope(
      overrides: [
        // 覆盖默认的authLocalDataSourceProvider，使用已初始化的实例
        authLocalDataSourceProvider.overrideWithValue(authLocalDataSource),
      ],
      child: AppInitializer(
        child: FlowPlanApp(),
      ),
    ),
  );

  // 应用关闭时的回调
  WidgetsBinding.instance.addObserver(
    _AppLifecycleObserver(authLocalDataSource: authLocalDataSource),
  );
}

/// 应用生命周期观察者
class _AppLifecycleObserver extends WidgetsBindingObserver {
  final AuthLocalDataSource authLocalDataSource;

  _AppLifecycleObserver({required this.authLocalDataSource});

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.detached) {
      // 应用即将关闭，确保数据已写入磁盘
      print('应用即将关闭');
      authLocalDataSource.close();
    }
  }
}
